<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="试卷名称" prop="paperName">
        <el-input
          v-model="queryParams.paperName"
          placeholder="请输入试卷名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="章节" prop="chapterId">
        <el-cascader
          :options="cascaders1"
          @change="fonce()"
          ref="casdaer"
          :props="{ checkStrictly: true }"
          clearable
        ></el-cascader>
      </el-form-item>
      <el-form-item label="试卷状态" prop="paperState">
        <el-select
          v-model="queryParams.paperState"
          placeholder="请选择试卷状态"
          clearable
          size="small"
        >
          <el-option label="请选择" value="" />
          <el-option label="组卷中" value="0" />
          <el-option label="正常" value="1" />
          <el-option label="停用" value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="试卷类型" prop="paperType">
        <el-select
          v-model="queryParams.paperType"
          placeholder="请选择试卷类型"
          clearable
          size="small"
        >
          <el-option label="请选择" value="" />
          <el-option label="单元测" value="0" />
          <el-option label="模拟测" value="1" />
          <el-option label="小测试" value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="创建人" prop="userId">
        <el-select
          clearable
          v-model="queryParams.userId"
          placeholder="请选择创建人"
        >
          <el-option
            v-for="item in users"
            :key="item.userId"
            :label="item.userName"
            :value="item.userId"
            >{{ item.userName }}</el-option
          >
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['paper:paper:add']"
          >组卷</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['paper:paper:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['paper:paper:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['paper:paper:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="paperList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="试卷名称" align="center" prop="paperName" />
      <el-table-column label="课程" align="center" prop="courseName" />
      <el-table-column label="章节" align="center" prop="chapterName" />
      <el-table-column
        label="试卷状态"
        align="center"
        prop="paperState"
        :formatter="onState"
      />
      <el-table-column
        label="试卷类型"
        align="center"
        prop="paperType"
        :formatter="onType"
      />
      <el-table-column label="创建人" align="center" prop="userName" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-s-tools"
            @click="zujuan(scope.row)"
            :disabled="scope.row.paperState != 0"
            v-hasPermi="['paper:paper:zujuan']"
            >自动组卷</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['paper:paper:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="show(scope.row)"
            v-hasPermi="['paper:paper:show']"
            >查看</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['paper:paper:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改paper对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="试卷名称" prop="paperName">
          <el-input v-model="form.paperName" placeholder="请输入试卷名称" />
        </el-form-item>
        <el-form-item label="类型" prop="paperType">
          <el-radio-group @change="casder" v-model="form.paperType">
            <el-radio :label="'0'">单元测试</el-radio>
            <el-radio :label="'1'">模拟测试</el-radio>
            <el-radio :label="'2'">小测试</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="章节" prop="chapterId">
          <el-cascader
            :props="props"
            v-model="form.chapterId"
            :options="cascaders"
            @change="getNums()"
            clearable
          ></el-cascader>
        </el-form-item>
        <el-form-item label="试卷状态" prop="paperState">
          <el-radio-group v-model="form.paperState">
            <el-radio :label="0">组卷中</el-radio>
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="2">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          v-for="item in tkTypes"
          :key="item.tkTypeId"
          :label="item.tkTypeName"
          prop="tkTypeNum"
        >
          <el-input-number
            :disabled="item.paperNums == 0"
            :min="0"
            :max="item.paperNums"
            placeholder="0"
            v-model="item.paperNum"
          />
          <span>{{ item.paperNums }}</span>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="examName" :visible.sync="isShow">
      <el-container style="height: 500px; border: 1px solid #eee">
               
        <el-header
          key=""
          height="100"
          style="color: #333; text-align: center; line-height: 30px"
        >
                   
          <el-row>
                       
            <el-col span="4"
              ><span style="font-weight: bold; color: red"
                >试卷标题: {{ examName }}              
              </span></el-col
            >
            <el-col :offset="10" :span="4"
              ><span style="font-weight: bold; color: red"
                >题目数量: {{ examData.length }}</span
              ></el-col
            >
                     
          </el-row>
          <el-row>
                       
            <el-col :span="4"
              ><span style="font-weight: bold; color: red"
                >总分: {{ fen }}</span
              ></el-col
            >
                        <el-col :span="4"></el-col>          
          </el-row>
                   
          <el-row>
                       
            <el-col :span="4" style="font-weight: bold; color: red"
              >平均难度: 正常</el-col
            >
                       
            <el-col :offset="10" :span="4">
              <el-button size="mini" type="primary" plain @click="addQuestion"
                >添加试题</el-button
              ></el-col
            >
                       
            <el-col :span="4"
              ><el-button
                type="danger"
                size="mini"
                plain
                @click="deleteQuestion"
                >删除试题</el-button
              ></el-col
            > 
          </el-row>
                 
        </el-header>
               
        <el-main
          style="background-color: #e9eef3; color: #333; line-height: 20px"
        >
                   
          <el-row>
                       
            <el-col :span="4" style="font-weight: bold">
                           
              <el-checkbox
                :indeterminate="true"
                v-model="checkAll"
                @change="handleCheckAllChange"
              ></el-checkbox>
                            全选            
            </el-col>
                       
            <el-col :offset="3" :span="4" style="font-weight: bold"
              >课程:</el-col
            >
                     
          </el-row>
                 
          <div v-for="(item, index) in examData" :key="index">
            <el-row>
              <el-col :span="1"> </el-col>
              <el-col :span="22"
                ><p>
                  <el-checkbox
                    @change="handleCheckedCitiesChange"
                    v-model="item.is"
                  />{{ index + 1 }}、【{{ item.tkTypeName }}】{{
                    item.tkTitle
                  }}
                  答案：{{ item.tkKey }}(分值：{{ item.score }})
                </p></el-col
              >
            </el-row>
            <el-row>
              <el-col :span="24">
                <ul style="list-style: none">
                  <li v-for="option in item.options" :key="option.optionId">
                    {{ option.optionName }}
                  </li>
                </ul>
              </el-col>
            </el-row>
          </div>
        </el-main>
      </el-container>

     
    </el-dialog>
  </div>
</template>

<script>
import {
  listPaper,
  getPaper,
  delPaper,
  addPaper,
  updatePaper,
  exportPaper,
  tkNums,
  zujuan,
  TypeNums,
  getTk,
} from "@/api/paper/paper";

import { cascade, cascade2, listTkType } from "@/api/tk/tk";
import { listUser } from "@/api/system/user";

export default {
  name: "Paper",
  data() {
    return {
      fen: 0,
      //是否显示试卷
      isShow: false,
      //试卷详情
      exam: {},
      examData: [],
      //试卷标题
      examName: "",
      tkNums: [],
      //题型
      tkTypes: [],
      //用户数据
      users: [],
      //级联是否多选
      props: { multiple: false },
      //级联数据
      cascaders: [],
      cascaders1: [],
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // paper表格数据
      paperList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        paperName: null,
        courseId: null,
        chapterId: null,
        paperState: null,
        paperType: null,
        userId: null,
      },
      p: {
        paperName: null,
        courseId: null,
        chapterId: null,
        paperState: null,
        paperType: null,
        userId: null,
        paperId: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
    };
  },
  created() {
    this.getList();
  },
  methods: {
    show(row) {
      this.isShow = true;
      this.examName = row.paperName;
      this.exam = row;
      getTk({ paperId: row.paperId })
        .then((res) => {
          this.examData = res;
        })
        .then(() => {
          var num = 0;
          this.examData.forEach((element) => {
            num += parseInt(element.score);
          });
          this.fen = num;
          console.log(fen);
        });
    },
    zujuan(row) {
      this.p.courseId = row.courseId;
      this.p.chapterId = row.chapterId;
      this.p.paperId = row.paperId;
      zujuan(this.p).then((res) => {
        if (res.code == 200) {
          this.$modal.msgSuccess("组卷成功");
        }
      });
    },
    getNums() {
      const l = this.form.chapterId.length;
      const qu = {};
      if (l == 3) {
        if (this.props.multiple) {
        } else {
          qu.chapterId = this.form.chapterId[2];
        }
      } else {
        qu.courseId = this.form.chapterId[1];
      }
      tkNums(qu).then((res) => {
        this.tkNums = res;
        for (var i = 0; i < this.tkTypes.length; i++) {
           this.tkTypes[i].paperNums = 0;
          this.tkNums.forEach(element=>{
            if(element.tkTypeId==this.tkTypes[i].tkTypeId){
               console.log(this.tkTypes[i].tkTypeName);
               console.log(this.tkTypes[i].tkTypeId);
               console.log(element.paperNum);
              this.tkTypes[i].paperNums = element.paperNum;
            }
            this.$forceUpdate();
          })
         
        }
      });
    },
    /** 获取级联数据 */
    getCascade() {
      cascade().then((res) => {
        this.cascaders1 = res;
      });
    },
    /** 回显题型数量 */
    typeNums(paperId) {
      TypeNums(paperId).then((res) => {
        for (var i = 0; i < res.rows.length; i++) {
          this.tkTypes.forEach((element) => {
            if (element.tkTypeId == res.rows[i].tkTypeId) {
              element.paperNum = res.rows[i].paperNum;
              element.id = res.rows[i].id;
            }
          });
        }
      });
    },
    fonce() {
      const date = this.$refs["casdaer"].getCheckedNodes()[0];
      if (date.level == 1) {
        // this.queryParams.typeId = date.value;
      } else if (date.level == 2) {
        this.queryParams.courseId = date.value;
      } else {
        this.queryParams.chapterId = date.value;
      }
    },
    /** 获取题型 */
    getTkType() {
      listTkType().then((res) => {
        this.tkTypes = res.rows;
      });
    },
    /** 获取用户列表 */
    getUser() {
      listUser().then((res) => {
        this.users = res.rows;
      });
    },
    /** 获取级联数据 */
    casder(param) {
      if (param == 1) {
        cascade2().then((res) => {
          this.cascaders = res;
        });
        this.props.multiple = false;
      } else {
        cascade().then((res) => {
          this.cascaders = res;
        });
        if (param == 0) {
          this.props.multiple = false;
        } else {
          this.props.multiple = true;
        }
      }
    },
    /** 查询paper列表 */
    getList() {
      this.getCascade();
      this.loading = true;
      listPaper(this.queryParams)
        .then((response) => {
          this.paperList = response.rows;
          this.total = response.total;
          this.loading = false;
        })
        .then(() => {
          this.getUser();
          this.getTkType();
        });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.getUser();
      this.form = {
        paperId: null,
        paperName: null,
        courseId: null,
        chapterId: null,
        paperState: 0,
        paperType: "0",
        userId: null,
        paperStr: null,
        paperInt: null,
        tkNumsList: [],
      };
      this.props.multiple = false;
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.paperId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.casder(0);
      this.open = true;
      this.title = "组卷";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      //回显渲染级联
      this.casder(row.paperType);
      //回显渲染类型数量
      this.typeNums(row.paperId);
      const paperId = row.paperId || this.ids;
      getPaper(paperId).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.form.tkNumsList = this.tkTypes;
          if (this.form.chapterId.length <= 3) {
            console.log(this.form.chapterId.length);
            this.form.courseId = this.form.chapterId[1];
            this.form.chapterId = this.form.chapterId[2];
          }
          if (this.form.paperId != null) {
            updatePaper(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPaper(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const paperIds = row.paperId || this.ids;
      this.$modal
        .confirm('是否确认删除paper编号为"' + paperIds + '"的数据项？')
        .then(function () {
          return delPaper(paperIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$modal
        .confirm("是否确认导出所有paper数据项？")
        .then(() => {
          this.exportLoading = true;
          return exportPaper(queryParams);
        })
        .then((response) => {
          this.$download.name(response.msg);
          this.exportLoading = false;
        })
        .catch(() => {});
    },
    onState(row, column) {
      var res = "";
      const state = row.paperState;
      if (state == 0) {
        res = "组卷中";
      } else if (state == 1) {
        res = "使用";
      } else if (state == 2) {
        res = "停用";
      }
      return res;
    },
    onType(row, column) {
      var res = "";
      const type = row.paperType;
      if (type == 0) {
        res = "单元测试";
      } else if (type == 1) {
        res = "模拟测试";
      } else if (type == 2) {
        res = "小测试";
      }
      return res;
    },
  },
};
</script>
